package com.songqi.common.oss.config;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.util.StringUtils;
import com.songqi.common.oss.OssClient;
import com.songqi.common.oss.properties.S3Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2023/7/5 09:13
 */
@ConditionalOnProperty(name = "s3.provider", havingValue = "aws")
@EnableConfigurationProperties(S3Properties.class)
@Slf4j
public class AwsS3AutoConfiguration implements OssClient, InitializingBean, DisposableBean {
    @Resource
    private S3Properties s3Properties;
    private AmazonS3 ossClient;

    @Override
    public String upload(String bucket, String dir, MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new IllegalArgumentException("文件不能为空!");
        }
        String objectName = UUID.fastUUID()+ file.getOriginalFilename();
        if(StrUtil.isNotBlank(dir)){
            if(! dir.endsWith("/")){
                dir = dir + "/" ;
            }
            if(dir.startsWith("/")){
                dir = dir.substring(1);
            }
            objectName = dir + objectName;
        }
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentLength(file.getSize());
        bucket = StringUtils.isNullOrEmpty(bucket) ? s3Properties.getBucket() : bucket;
        try {
            PutObjectRequest request = new PutObjectRequest(bucket, objectName, file.getInputStream(), objectMetadata);
            PutObjectResult result = ossClient.putObject(request);
            log.info("文件上传结果：{}", JSONUtil.toJsonStr(result));
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, objectName);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

    @Override
    public void destroy() throws Exception {
        if(ossClient != null){
            ossClient.shutdown();
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(ossClient == null){
            AWSCredentials credentials = new BasicAWSCredentials(s3Properties.getAccessKey(), s3Properties.getSecretKey());
            AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
            AwsClientBuilder.EndpointConfiguration endpointConfig =
                    new AwsClientBuilder.EndpointConfiguration(s3Properties.getEndpoint(), Regions.EU_WEST_2.getName());
            ClientConfiguration config = new ClientConfiguration();
            config.setSignerOverride("S3SignerType");
            config.setProtocol(Protocol.HTTP);
            config.withUseExpectContinue(false);
            config.disableSocketProxy();
            ossClient = AmazonS3Client.builder()
                    .withEndpointConfiguration(endpointConfig)
                    .withClientConfiguration(config)
                    .withCredentials(credentialsProvider)
                    .disableChunkedEncoding()
                    .withPathStyleAccessEnabled(true)
                    .withForceGlobalBucketAccessEnabled(true)
                    .build();
        }


    }
}
